import os
import time
import pymongo
import logging
import collections
import re
import math
import jieba
import setting
import upyun
from flask import Flask, jsonify, request
from wordcloud import WordCloud

app = Flask(__name__)
mongo_client = pymongo.MongoClient(setting.mongo)
db = mongo_client[setting.db]
col = db["record"]
jieba.setLogLevel(logging.INFO)
up = upyun.UpYun(setting.upyun_service, setting.upyun_username, setting.upyun_password, timeout=30,
                 endpoint=upyun.ED_AUTO)


def stop_words_list():
    stop_words = [line.strip() for line in open('chinsesstop.txt', encoding='UTF-8').readlines()]
    stop_words = [k for s in stop_words for k in s]
    return stop_words


stopwords = stop_words_list()


@app.route('/report/<user_id>')
def report(user_id):
    text = ""
    channel_count = {
        "news_hot": 0,
        "news_society": 0,
        "news_entertainment": 0,
        "news_tech": 0,
        "news_military": 0,
        "news_sports": 0,
        "news_car": 0,
        "news_food": 0
    }
    after = request.args.get("after")
    for x in col.find({
        "user_id": int(user_id),
        "read_at": {
            "$gt": int(after)
        }
    }):
        text += x["news_content"]
        channel_count[x["news_channel"]] += 1

    if len(text) == 0:
        t = {
            "word_count": len(text),
            "word_cloud": "",
            "channel_count": channel_count
        }
        return jsonify(t)
    wc = word_cloud(text, user_id)
    resp = {
        "word_count": len(text),
        "word_cloud": wc,
        "channel_count": channel_count
    }
    return jsonify(resp)


def word_cloud(text, user_id):
    top_word_frequency_percentage = 30
    top_word_frequency_percentage /= 100
    ts = str(int(time.time()))
    file_name = str(user_id) + "-" + ts + ".png"
    pic_save_path = "./" + file_name
    seg = jieba.cut(text)
    seg = " ".join(seg)
    seg = seg.strip()
    seg = re.sub(r"[0-9\s+\.\!\/_,$%^*()?;；:-【】+\"\']+|[+——！，;:：。？、~@#￥%……&*（）]+", " ", seg)
    seg = re.sub(r'[^\u4e00-\u9fa5]', ' ', seg)
    seg = seg.split(" ")
    seg = list(filter(None, seg))
    seg = [v for v in seg if v not in stopwords]
    word_counts = collections.Counter(seg)
    wc = WordCloud(
        max_words=math.ceil(len(word_counts) * top_word_frequency_percentage),
        width=500,
        height=350,
        max_font_size=50,
        min_font_size=10,
        font_path='./MSYH.TTC',
        background_color='white',
    )
    wc.generate_from_frequencies(word_counts)
    wc.to_file(pic_save_path)
    headers = {'x-upyun-meta-ttl': '2'}
    with open(pic_save_path, 'rb') as f:
        up.put("/img/wordcloud/" + file_name, f, checksum=True, headers=headers)
    os.remove(pic_save_path)
    return setting.cdn_domain + "/img/wordcloud/" + file_name


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=setting.port)
